<template>
  <div class="home-page">
    <!-- 顶部用户信息区域 -->
    <div class="header-section">
      <div class="user-info">
        <span class="user-name">{{ username }}</span>
        <div class="date-info">{{ currentTime }}</div>
      </div>
    </div>

    <!-- 区域卡片横向滚动 -->
    <div class="rooms-container" v-if="userRegions && userRegions.length > 0">
      <div class="rooms-scroll">
        <div 
          class="room-card" 
          v-for="(region, index) in userRegions" 
          :key="index" 
          @click="handleRegionClick(region)"
        >
          <div class="room-image">
            <img 
              v-if="region.picture" 
              :src="region.picture" 
              :alt="region.regionName"
              @error="handleImageError"
            />
            <div v-else class="room-placeholder">
              <el-icon><Location /></el-icon>
            </div>
          </div>
          <div class="room-name">{{ region.regionName || region.name || '未知区域' }}</div>
        </div>
      </div>
    </div>

    <!-- 控制面板区域 -->
    <div class="control-panel">
      <!-- 环境控制卡片 -->
      <div class="control-card environment-card">
        <!-- 天气信息行 -->
        <div class="control-row weather-row">
          <div class="weather-info-row">
            <div class="control-item weather-temp">
              <div class="control-label">温度</div>
              <div class="control-value">{{ weatherData.temperature }}°</div>
              <div class="control-status">{{ weatherData.city }}</div>
            </div>
            <div class="control-item weather-region">
              <div class="custom-select-container">
                <div 
                  class="custom-select"
                  @click="toggleDropdown"
                  :class="{ 'is-open': dropdownOpen }"
                >
                  <span class="select-text">
                    {{ selectedRegionText || '选择区域' }}
                  </span>
                  <svg class="select-arrow" :class="{ 'rotated': dropdownOpen }" viewBox="0 0 24 24">
                    <path d="M7 10l5 5 5-5z" fill="currentColor"/>
                  </svg>
                </div>
                <div class="dropdown-menu" v-show="dropdownOpen">
                  <div 
                    v-for="region in userRegions"
                    :key="region.id"
                    class="dropdown-item"
                    :class="{ 'selected': selectedRegionId === region.id }"
                    @click="selectRegion(region)"
                  >
                    {{ region.regionName || region.name }}
                  </div>
                </div>
              </div>
            </div>
            <div class="control-item weather-humidity">
              <div class="control-label">湿度</div>
              <div class="control-value">{{ weatherData.humidity }}%</div>
              <div class="control-status">{{ weatherData.description }}</div>
            </div>
          </div>
          
          <!-- 天气预警信息 - 直接在天气行内部 -->
          <div class="weather-alert-container" v-if="weatherData.tips">
            <div class="clay-weather-alert">
              <span class="weather-alert-text">{{ weatherData.tips }}</span>
            </div>
          </div>
          
          <!-- 工作提示模块 - 直接在天气行内部 -->
          <div class="work-tips-container-inline">
            <div class="work-tips-header">
              <span class="work-tips-title">工作提示</span>
            </div>
            <div class="work-tips-content">
              <div class="work-tip-item">
                <span class="work-tip-text" v-html="currentWorkTip || '暂无工作内容'"></span>
              </div>
            </div>
          </div>
        </div>
        
      </div>
    </div>

    
    <!-- 详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" width="430px" :close-on-click-modal="true" class="info-detail-dialog" :show-close="true" @close="resetDetailDialog" :footer="null">
      <template #title>
        <div class="info-detail-title">详情</div>
      </template>
      <el-skeleton v-if="detailLoading" rows="6" animated style="margin: 32px 0" />
      <div v-if="detailData" class="info-detail-content">
        <div class="info-detail-main-img-wrap">
          <div class="info-detail-main-img-interactive">
            <el-image
              v-if="detailData.picture"
              :src="detailData.picture"
              fit="cover"
              :preview-src-list="[detailData.picture]"
              :initial-index="0"
              class="info-detail-main-img-el"
              :style="{ width: '220px', height: '120px' }"
            />
            <div v-else class="info-detail-main-img-placeholder">
              <el-icon><Camera /></el-icon>
              <span>暂无图片</span>
            </div>
          </div>
          <span class="info-detail-status-badge-float" :class="'badge-status-' + detailData.status">
            {{ infoStatusMap[detailData.status]?.text || '未知' }}
          </span>
        </div>
        <div class="info-detail-section">
          <div class="info-detail-remarks-content">
            <div class="info-detail-remarks-text">
              {{ detailData.remarks || detailData.remark || '暂无备注' }}
            </div>
          </div>
        </div>
        <div class="info-detail-section">
          <div class="info-detail-section-title">检测信息</div>
          <div class="info-detail-row">
            <span class="info-detail-label">检测人员</span>
            <span class="info-detail-value">{{ detailDetectionUser?.nickName || '-' }}</span>
            <span class="info-detail-label">员工编号</span>
            <span class="info-detail-value">{{ detailData.detectionBy || '-' }}</span>
          </div>
          <div class="info-detail-row">
            <span class="info-detail-label">检测时间</span>
            <span class="info-detail-value">{{ detailData.detectionTime ? (detailData.detectionTime.split('T')[0] + ' ' + (detailData.detectionTime.split('T')[1]||'').split('+')[0]) : '-' }}</span>
          </div>
          <div class="info-detail-album-row">
            <span class="info-detail-label">检测相册</span>
            <div class="info-detail-album-list" style="position:relative;display:flex;align-items:center;">
              <el-image
                v-for="(img, idx) in (inspecAlbumExpanded ? (detailData.cInspecAlbumList || []) : (detailData.cInspecAlbumList || []).slice(0,3))"
                :key="idx"
                :src="img.url || img.picture || ''"
                fit="cover"
                class="info-detail-album-img"
                :preview-src-list="(detailData.cInspecAlbumList||[]).map(i=>i.url||i.picture||'')"
                :initial-index="idx"
                @click.stop
              />
              <span v-if="!(detailData.cInspecAlbumList && detailData.cInspecAlbumList.length)">无</span>
              <el-icon
                v-if="detailData.cInspecAlbumList && detailData.cInspecAlbumList.length > 3"
                class="album-expand-arrow"
                :class="{expanded: inspecAlbumExpanded}"
                style="margin-left:8px;cursor:pointer;"
                @click.stop="inspecAlbumExpanded = !inspecAlbumExpanded"
              >
                <svg width="38" height="38" viewBox="0 0 38 38">
                  <defs>
                    <linearGradient id="arrowBlue" x1="0" y1="0" x2="1" y2="1">
                      <stop offset="0%" stop-color="#60a5fa"/>
                      <stop offset="100%" stop-color="#1e3a8a"/>
                    </linearGradient>
                  </defs>
                  <circle cx="19" cy="19" r="18" fill="#eaf3fd" fill-opacity="0.85"/>
                  <circle cx="19" cy="19" r="18" fill="url(#arrowBlue)" fill-opacity="0.12"/>
                  <path d="M13 17l6 6 6-6" stroke="url(#arrowBlue)" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
                </svg>
              </el-icon>
            </div>
          </div>
        </div>
        <div class="info-detail-section">
          <div class="info-detail-section-title">维修信息</div>
          <div class="info-detail-row">
            <span class="info-detail-label">维修人员</span>
            <span class="info-detail-value">{{ detailMaintenanceUser?.nickName || '-' }}</span>
            <span class="info-detail-label">员工编号</span>
            <span class="info-detail-value">{{ detailData.maintenanceBy || '-' }}</span>
          </div>
          <div class="info-detail-row">
            <span class="info-detail-label">维修时间</span>
            <span class="info-detail-value">{{ detailData.maintenanceTime ? (detailData.maintenanceTime.split('T')[0] + ' ' + (detailData.maintenanceTime.split('T')[1]||'').split('+')[0]) : '-' }}</span>
          </div>
          <div class="info-detail-album-row">
            <span class="info-detail-label">维修相册</span>
            <div class="info-detail-album-list" style="position:relative;display:flex;align-items:center;">
              <el-image
                v-for="(img, idx) in (maintainAlbumExpanded ? (detailData.cMaintainAlbumList || []) : (detailData.cMaintainAlbumList || []).slice(0,3))"
                :key="idx"
                :src="img.url || img.picture || ''"
                fit="cover"
                class="info-detail-album-img"
                :preview-src-list="(detailData.cMaintainAlbumList||[]).map(i=>i.url||i.picture||'')"
                :initial-index="idx"
                @click.stop
              />
              <span v-if="!(detailData.cMaintainAlbumList && detailData.cMaintainAlbumList.length)">无</span>
              <el-icon
                v-if="detailData.cMaintainAlbumList && detailData.cMaintainAlbumList.length > 3"
                class="album-expand-arrow"
                :class="{expanded: maintainAlbumExpanded}"
                style="margin-left:8px;cursor:pointer;"
                @click.stop="maintainAlbumExpanded = !maintainAlbumExpanded"
              >
                <svg width="38" height="38" viewBox="0 0 38 38">
                  <defs>
                    <linearGradient id="arrowBlue2" x1="0" y1="0" x2="1" y2="1">
                      <stop offset="0%" stop-color="#60a5fa"/>
                      <stop offset="100%" stop-color="#1e3a8a"/>
                    </linearGradient>
                  </defs>
                  <circle cx="19" cy="19" r="18" fill="#eaf3fd" fill-opacity="0.85"/>
                  <circle cx="19" cy="19" r="18" fill="url(#arrowBlue2)" fill-opacity="0.12"/>
                  <path d="M13 17l6 6 6-6" stroke="url(#arrowBlue2)" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
                </svg>
              </el-icon>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="info-detail-empty">暂无详细信息</div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  Warning, Document, Camera, Location, User
} from '@element-plus/icons-vue'
// 夜间模式已禁用
import { listRegion_user } from '@/api/region/region_user'
import { getRegion } from '@/api/region/region'
import { listRegion_picture } from '@/api/region/region_picture'
import { listInformation, getInformation } from '@/api/information/information'
import { ElMessage } from 'element-plus'
import { getUserProfile, getAuthRole, getUser } from '@/api/system/user'
import UserAvatar from '@/components/UserAvatar.vue'
import { getUserInfo } from '@/utils/auth'

const router = useRouter()

// 主题切换功能已禁用

const userInfo = ref({
  userId: null,
  username: "",
  nickName: "",
  realName: "",
  roleId: null,
  roleName: "",
  roleKey: "",
  avatar: ""
})
const userRoleKey = ref("")

const loadUserInfoAndRole = async () => {
  try {
    // 1. 优先API获取
    const profileRes = await getUserProfile()
    if (profileRes.code === 200 && profileRes.data) {
      const profile = profileRes.data
      
      // 从 localStorage 获取备用数据
      const storedUser = getUserInfo()
      
      // 获取用户昵称：优先使用 API 返回的值，如果为空则使用 localStorage 的值
      let nickNameValue = profile.nickName || profile.nickname
      if (!nickNameValue || nickNameValue === null || nickNameValue === undefined || String(nickNameValue).trim() === '') {
        if (storedUser) {
          nickNameValue = storedUser.nickName || storedUser.nickname || ''
        } else {
          nickNameValue = ''
        }
      }
      if (nickNameValue) {
        nickNameValue = String(nickNameValue).trim()
      }
      
      userInfo.value = {
        userId: profile.userId,
        username: profile.userName || profile.username || "",
        nickName: nickNameValue || "",
        realName: profile.realName || nickNameValue || profile.userName || "",
        roleId: profile.roleId || profile.role_id || null,
        roleName: profile.roleName || "",
        roleKey: "",
        avatar: profile.avatar || ""
      }
      // 2. 再查角色
      if (userInfo.value.userId) {
        const roleRes = await getAuthRole(userInfo.value.userId)
        if (roleRes.code === 200 && roleRes.user.roles && roleRes.user.roles.length > 0) {
          userInfo.value.roleKey = roleRes.user.roles[0].roleKey || ""
          userInfo.value.roleName = roleRes.user.roles[0].roleName || ""
          userRoleKey.value = userInfo.value.roleKey
        }
      }
    }
    // 3. 回退localStorage
    if (!userInfo.value.userId) {
      const local = localStorage.getItem('userInfo')
      if (local) {
        const u = JSON.parse(local)
        userInfo.value.userId = u.userId
        userInfo.value.username = u.userName || u.username || ""
        userInfo.value.nickName = u.nickName || u.nickname || ""
        userInfo.value.realName = u.realName || u.nickName || u.nickname || u.userName || ""
        userInfo.value.roleId = u.roleId || u.role_id || null
        userInfo.value.roleName = u.roleName || ""
        userInfo.value.roleKey = u.roleKey || ""
        userInfo.value.avatar = u.avatar || ""
        userRoleKey.value = u.roleKey || ""
      }
    }
  } catch (e) {
    // fallback
  }
}

// 用户负责区域
const userRegions = ref([])

// 监听localStorage变化
const updateUserInfo = () => {
  userInfo.value = getUserInfo()
}

// 计算用户名（优先显示用户昵称）
const username = computed(() => {
  const user = userInfo.value
  if (user) {
    // 优先显示用户昵称
    if (user.nickName && user.nickName.trim() !== '') {
      return user.nickName
    }
    if (user.nickname && user.nickname.trim() !== '') {
      return user.nickname
    }
    // 如果没有昵称，显示真实姓名
    if (user.realName && user.realName.trim() !== '') {
      return user.realName
    }
    // 最后显示账号名称
    return user.userName || user.username || '用户'
  }
  return '用户'
})

// 计算用户头像
const userAvatar = computed(() => {
  const user = userInfo.value
  if (user && user.avatar) return user.avatar
  const storedAvatar = localStorage.getItem('userAvatar')
  if (storedAvatar) return storedAvatar
  return ''
})

const currentTime = ref('')

// 天气数据
const weatherData = ref({
  temperature: '--',
  humidity: '--',
  city: '获取中...',
  description: '加载中',
  alerts: [], // 天气预警信息
  tips: '获取天气提示中...' // 天气提示
})

// 选中的区域ID
const selectedRegionId = ref(null)

// 下拉框相关状态
const dropdownOpen = ref(false)
const selectedRegionText = ref('')

// 工作提示相关
const workTips = ref([])
const currentWorkTip = ref('')
const workTipIndex = ref(0)
const workTipTimer = ref(null)


// 快捷操作
const quickActions = ref([
  {
    label: '安全检查',
    icon: Document,
    type: 'primary',
    action: '/form1'
  },
  {
    label: '隐患上报',
    icon: Warning,
    type: 'warning',
    action: '/form2'
  },
  {
    label: '现场拍照',
    icon: Camera,
    type: 'success',
    action: '/camera'
  },
  {
    label: '位置签到',
    icon: Location,
    type: 'info',
    action: '/location'
  }
])

// 信息状态映射
const infoStatusMap = {
  0: { text: '待维修', color: '#ff4d4f', bg: 'rgba(255,77,79,0.10)' },
  1: { text: '已维修', color: '#52c41a', bg: 'rgba(82,196,26,0.10)' },
  2: { text: '待审核', color: '#faad14', bg: 'rgba(250,173,20,0.10)' },
  3: { text: '不通过', color: '#8c8c8c', bg: 'rgba(140,140,140,0.10)' }
}

// 最近活动（工作记录）
const activities = ref([])

// 时间格式化
function formatTimeAgo(timeStr) {
  if (!timeStr) return ''
  const time = new Date(timeStr.replace(/-/g, '/'))
  const now = new Date()
  const diff = (now - time) / 1000 // 秒
  if (diff < 60) return Math.floor(diff) + '秒前'
  if (diff < 3600) return Math.floor(diff / 60) + '分钟前'
  if (diff < 86400) return Math.floor(diff / 3600) + '小时前'
  if (diff < 2592000) return Math.floor(diff / 86400) + '天前'
  return timeStr.split(' ')[0]
}

// 获取最新4条工作记录
const fetchRecentActivities = async () => {
  let query = { pageNum: 1, pageSize: 100 } // 拉取足够多，前端再排序
  if ([
    'inspector', 'inspec', 'inspect', '巡检', '巡检人员'
  ].includes(userRoleKey.value)) {
    query.detectionBy = userInfo.value.userId
  } else if ([
    'maintainer', 'maintain', 'maintenance', '维修', '维修人员'
  ].includes(userRoleKey.value)) {
    query.maintenanceBy = userInfo.value.userId
  }
  try {
    const res = await listInformation(query)
    if (res.code === 200 && Array.isArray(res.rows)) {
      let sortedRows = []
      if ([
        'inspector', 'inspec', 'inspect', '巡检', '巡检人员'
      ].includes(userRoleKey.value)) {
        sortedRows = [...res.rows].sort((a, b) => {
          const ta = new Date(a.detectionTime || a.maintenanceTime || a.createTime).getTime()
          const tb = new Date(b.detectionTime || b.maintenanceTime || b.createTime).getTime()
          return tb - ta
        })
      } else if ([
        'maintainer', 'maintain', 'maintenance', '维修', '维修人员'
      ].includes(userRoleKey.value)) {
        sortedRows = [...res.rows].sort((a, b) => {
          const ta = new Date(a.maintenanceTime || a.detectionTime || a.createTime).getTime()
          const tb = new Date(b.maintenanceTime || b.detectionTime || b.createTime).getTime()
          return tb - ta
        })
      } else {
        sortedRows = [...res.rows]
      }
      activities.value = sortedRows.slice(0, 4).map(item => {
        // 取时间字段
        let time = ''
        if ([
          'inspector', 'inspec', 'inspect', '巡检', '巡检人员'
        ].includes(userRoleKey.value)) {
          time = item.detectionTime || item.maintenanceTime || item.createTime
        } else if ([
          'maintainer', 'maintain', 'maintenance', '维修', '维修人员'
        ].includes(userRoleKey.value)) {
          time = item.maintenanceTime || item.detectionTime || item.createTime
        } else {
          time = item.maintenanceTime || item.detectionTime || item.createTime
        }
        return {
          id: item.id,
          title: `#${item.id} ${item.remarks || item.remark || ''}`,
          time: formatTimeAgo(time),
          icon: Document,
          type: 'primary',
          status: '',
          statusText: infoStatusMap[item.status]?.text || '未知',
          statusColor: infoStatusMap[item.status]?.color || '#888',
          statusBg: infoStatusMap[item.status]?.bg || '#eee',
        }
      })
    } else {
      activities.value = []
    }
  } catch {
    activities.value = []
  }
}

// 获取区域图片
const getRegionPicture = async (regionId) => {
  try {
    const response = await listRegion_picture({ regionId: regionId });
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      return response.rows[0].picture || response.rows[0].url;
    }
  } catch (error) {
    console.error(`获取区域${regionId}图片失败:`, error);
  }
  return null;
};

// 递归获取父区域图片
const getRegionPictureWithFallback = async (region) => {
  // 先尝试获取当前区域的图片
  let picture = await getRegionPicture(region.id);
  if (picture) return picture;
  
  // 如果没有图片且有父区域，则获取父区域图片
  if (region.parentId && region.parentId !== 0) {
    try {
      const parentResponse = await getRegion(region.parentId);
      if (parentResponse.code === 200 && parentResponse.data) {
        return await getRegionPictureWithFallback(parentResponse.data);
      }
    } catch (error) {
      console.error(`获取父区域${region.parentId}信息失败:`, error);
    }
  }
  
  return null;
};

// 获取用户负责的区域
const loadUserRegions = async (userId) => {
  if (!userId) return;

  try {
    // 查询该用户的区域关系
    const response = await listRegion_user({ userId: userId });
    
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      const regionIds = response.rows.map(item => item.regionId);
      
      // 获取区域详细信息
      const regionDetails = [];
      for (const regionId of regionIds) {
        try {
          const regionResponse = await getRegion(regionId);
          
          if (regionResponse.code === 200 && regionResponse.data) {
            // 确保状态字段存在，如果不存在则设置默认值
            const regionData = {
              ...regionResponse.data,
              status: regionResponse.data.regionStatus !== undefined ? regionResponse.data.regionStatus : 0
            };
            
            // 获取区域图片（包括父区域回退）
            regionData.picture = await getRegionPictureWithFallback(regionData);
            
            regionDetails.push(regionData);
          }
        } catch (error) {
          console.error(`获取区域${regionId}信息失败:`, error);
        }
      }
      
      // 按照状态优先级排序：待维修(2) > 待检查(1) > 安全(0)
      regionDetails.sort((a, b) => {
        const statusA = getRegionStatus(a);
        const statusB = getRegionStatus(b);
        
        // 状态优先级映射：2(待维修) > 1(待检查) > 0(安全)
        const priorityMap = { 2: 3, 1: 2, 0: 1 };
        const priorityA = priorityMap[statusA] || 0;
        const priorityB = priorityMap[statusB] || 0;
        
        return priorityB - priorityA; // 降序排列，优先级高的在前
      });
      
      userRegions.value = regionDetails;
    } else {
      userRegions.value = [];
    }
  } catch (error) {
    console.error("获取用户区域信息失败:", error);
    userRegions.value = [];
  }
};

// 更新当前时间
const updateTime = () => {
  const now = new Date()
  const options = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  }
  currentTime.value = now.toLocaleDateString('zh-CN', options)
}

// 处理快捷操作
const handleAction = (action) => {
  if (action.action.startsWith('/')) {
    router.push(action.action)
  }
}

// 处理区域点击
const handleRegionClick = (region) => {
  if (region.id) {
    router.push(`/region/${region.id}`)
  } else {
    ElMessage.warning('区域信息不完整')
  }
}

// 切换下拉框显示状态
const toggleDropdown = () => {
  dropdownOpen.value = !dropdownOpen.value
}

// 选择区域
const selectRegion = async (region) => {
  selectedRegionId.value = region.id
  selectedRegionText.value = region.regionName || region.name
  dropdownOpen.value = false
  
  try {
    // 获取该区域的父节点天气信息
    await fetchWeatherForSelectedRegion(region)
  } catch (error) {
    console.error('获取区域天气信息失败:', error)
    ElMessage.error('获取天气信息失败')
  }
}

// 处理区域选择变化（保留兼容性）
const handleRegionChange = async (regionId) => {
  if (!regionId) return
  
  try {
    // 找到选中的区域
    const selectedRegion = userRegions.value.find(region => region.id === regionId)
    if (!selectedRegion) return
    
    // 获取该区域的父节点天气信息
    await fetchWeatherForSelectedRegion(selectedRegion)
  } catch (error) {
    console.error('获取区域天气信息失败:', error)
    ElMessage.error('获取天气信息失败')
  }
}

// 获取区域状态类
const getRegionStatusClass = (status) => {
  // 确保status是数字类型
  const statusNum = parseInt(status);
  
  const statusMap = {
    0: 'safe',      // 安全
    1: 'unchecked', // 未检查
    2: 'maintenance' // 待维修
  }
  
  return statusMap[statusNum] || 'unknown';
}

// 获取区域状态文本
const getRegionStatusText = (status) => {
  // 确保status是数字类型
  const statusNum = parseInt(status);
  
  const statusMap = {
    0: '安全',
    1: '未检查',
    2: '待维修'
  }
  
  return statusMap[statusNum] || '未知状态';
}

// 获取区域状态值（尝试多种可能的字段名）
const getRegionStatus = (region) => {
  // 尝试多种可能的状态字段名
  const possibleStatusFields = ['status', 'regionStatus', 'safetyStatus', 'state', 'regionState', 'safetyState'];
  
  for (const field of possibleStatusFields) {
    if (region[field] !== undefined) {
      return region[field];
    }
  }
  
  return 0;
}


// 获取区域状态样式类
const getAreaStatusClass = (status) => {
  switch (status) {
    case 0: return 'status-safe'
    case 1: return 'status-unchecked'
    case 2: return 'status-maintenance'
    default: return 'status-unknown'
  }
}

// 获取工作提示
const fetchWorkTips = async () => {
  try {
    const tips = []
    
    if (userRoleKey.value === 'inspector' || userRoleKey.value === 'inspec' || userRoleKey.value === 'inspect' || userRoleKey.value === '巡检' || userRoleKey.value === '巡检人员') {
      // 巡检人员：显示未检查的区域
      const uncheckedAreas = userRegions.value.filter(region => {
        const status = getRegionStatus(region)
        return status === 1 // 未检查状态
      })
      
      uncheckedAreas.forEach(region => {
        const regionName = region.regionName || region.name
        tips.push(`<span class="region-highlight">${regionName}</span>还未检查`)
      })
    } else if (userRoleKey.value === 'maintainer' || userRoleKey.value === 'maintain' || userRoleKey.value === 'maintenance' || userRoleKey.value === '维修' || userRoleKey.value === '维修人员') {
      // 维修人员：显示待维修的区域
      const maintenanceAreas = userRegions.value.filter(region => {
        const status = getRegionStatus(region)
        return status === 2 // 待维修状态
      })
      
      maintenanceAreas.forEach(region => {
        const regionName = region.regionName || region.name
        tips.push(`<span class="region-highlight">${regionName}</span>待维修`)
      })
    }
    
    workTips.value = tips
    
    // 如果有提示信息，开始轮播；否则显示默认信息
    if (tips.length > 0) {
      workTipIndex.value = 0
      currentWorkTip.value = tips[0]
      startWorkTipRotation()
    } else {
      currentWorkTip.value = ''
      stopWorkTipRotation()
    }
  } catch (error) {
    console.error('获取工作提示失败:', error)
  }
}

// 开始工作提示轮播
const startWorkTipRotation = () => {
  stopWorkTipRotation() // 先清除之前的定时器
  
  if (workTips.value.length > 1) {
    workTipTimer.value = setInterval(() => {
      workTipIndex.value = (workTipIndex.value + 1) % workTips.value.length
      currentWorkTip.value = workTips.value[workTipIndex.value]
    }, 5000) // 5秒间隔
  }
}

// 停止工作提示轮播
const stopWorkTipRotation = () => {
  if (workTipTimer.value) {
    clearInterval(workTipTimer.value)
    workTipTimer.value = null
  }
}

// 获取天气预警等级样式类
const getAlertLevelClass = (level) => {
  switch (level) {
    case '红色': return 'alert-red'
    case '橙色': return 'alert-orange'
    case '黄色': return 'alert-yellow'
    case '蓝色': return 'alert-blue'
    default: return 'alert-default'
  }
}

// 获取用户管控区域的父节点天气信息
const fetchWeatherForUserRegions = async () => {
  try {
    if (!userRegions.value || userRegions.value.length === 0) {
      console.log('暂无用户区域数据')
      return
    }

    // 获取用户管控区域的父节点
    const parentRegions = new Set()
    
    for (const region of userRegions.value) {
      // 尝试获取父节点信息
      if (region.parentId && region.parentId !== 0) {
        try {
          const parentRes = await getRegion(region.parentId)
          if (parentRes.code === 200 && parentRes.data) {
            parentRegions.add(parentRes.data)
          }
        } catch (error) {
          console.warn(`获取父节点 ${region.parentId} 失败:`, error)
        }
      } else if (region.regionName) {
        // 如果没有父节点，使用当前区域名称
        parentRegions.add(region)
      }
    }

    // 如果有父节点，使用第一个父节点的名称获取天气
    if (parentRegions.size > 0) {
      const firstParent = Array.from(parentRegions)[0]
      const cityName = extractCityName(firstParent.regionName || firstParent.name || '北京')
      await fetchWeatherData(cityName)
    } else {
      // 如果没有父节点，使用默认城市
      await fetchWeatherData('北京')
    }
  } catch (error) {
    console.error('获取用户区域天气信息失败:', error)
    // 设置默认天气信息
    weatherData.value = {
      temperature: 23,
      humidity: 38,
      city: '北京',
      description: '晴'
    }
  }
}

// 获取选中区域的父节点天气信息
const fetchWeatherForSelectedRegion = async (selectedRegion) => {
  try {
    let cityName = '北京' // 默认城市
    
    // 尝试获取父节点信息
    if (selectedRegion.parentId && selectedRegion.parentId !== 0) {
      try {
        const parentRes = await getRegion(selectedRegion.parentId)
        if (parentRes.code === 200 && parentRes.data) {
          cityName = extractCityName(parentRes.data.regionName || parentRes.data.name || '北京')
        }
      } catch (error) {
        console.warn(`获取父节点 ${selectedRegion.parentId} 失败:`, error)
        // 如果获取父节点失败，使用当前区域名称
        cityName = extractCityName(selectedRegion.regionName || selectedRegion.name || '北京')
      }
    } else {
      // 如果没有父节点，使用当前区域名称
      cityName = extractCityName(selectedRegion.regionName || selectedRegion.name || '北京')
    }
    
    // 获取天气数据
    await fetchWeatherData(cityName)
    console.log(`已获取区域 ${selectedRegion.regionName} 的天气信息，城市: ${cityName}`)
  } catch (error) {
    console.error('获取选中区域天气信息失败:', error)
    // 设置默认天气信息
    weatherData.value = {
      temperature: 23,
      humidity: 38,
      city: '北京',
      description: '晴',
      alerts: [],
      tips: '今日天气晴朗，工作愉快'
    }
  }
}

// 从区域名称中提取城市名称
const extractCityName = (regionName) => {
  // 尝试从区域名称中提取城市信息
  // 例如："北京市朝阳区" -> "北京"
  const cityPatterns = [
    /^(.+?)[市]/,  // 匹配"北京市"
    /^(.+?)[省]/,  // 匹配"河北省"
    /^(.+?)[区]/,  // 匹配"朝阳区"
    /^(.+?)[县]/,  // 匹配"某某县"
  ]
  
  for (const pattern of cityPatterns) {
    const match = regionName.match(pattern)
    if (match) {
      return match[1]
    }
  }
  
  // 如果没有匹配到，返回前几个字符作为城市名
  return regionName.substring(0, 2) || '北京'
}

// 天气数据缓存配置
const WEATHER_CACHE_KEY = 'weather_cache_'
const WEATHER_CACHE_DURATION = 30 * 60 * 1000 // 30分钟缓存时间

// 获取缓存的天气数据
const getCachedWeatherData = (cityName) => {
  try {
    const cacheKey = WEATHER_CACHE_KEY + cityName
    const cachedData = localStorage.getItem(cacheKey)
    
    if (cachedData) {
      const parsed = JSON.parse(cachedData)
      const now = Date.now()
      
      // 检查缓存是否过期
      if (now - parsed.timestamp < WEATHER_CACHE_DURATION) {
        console.log(`使用缓存的天气数据: ${cityName}`)
        return parsed.data
      } else {
        // 缓存过期，删除旧数据
        localStorage.removeItem(cacheKey)
        console.log(`天气缓存已过期: ${cityName}`)
      }
    }
  } catch (error) {
    console.error('读取天气缓存失败:', error)
  }
  return null
}

// 缓存天气数据
const setCachedWeatherData = (cityName, data) => {
  try {
    const cacheKey = WEATHER_CACHE_KEY + cityName
    const cacheData = {
      timestamp: Date.now(),
      data: data
    }
    localStorage.setItem(cacheKey, JSON.stringify(cacheData))
    console.log(`天气数据已缓存: ${cityName}`)
  } catch (error) {
    console.error('缓存天气数据失败:', error)
  }
}

// 清理过期的天气缓存
const clearExpiredWeatherCache = () => {
  try {
    const now = Date.now()
    const keysToRemove = []
    
    // 遍历localStorage查找过期的天气缓存
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i)
      if (key && key.startsWith(WEATHER_CACHE_KEY)) {
        try {
          const cachedData = localStorage.getItem(key)
          if (cachedData) {
            const parsed = JSON.parse(cachedData)
            if (now - parsed.timestamp >= WEATHER_CACHE_DURATION) {
              keysToRemove.push(key)
            }
          }
        } catch (error) {
          // 如果解析失败，也标记为删除
          keysToRemove.push(key)
        }
      }
    }
    
    // 删除过期的缓存
    keysToRemove.forEach(key => {
      localStorage.removeItem(key)
      console.log(`已清理过期天气缓存: ${key}`)
    })
    
    if (keysToRemove.length > 0) {
      console.log(`共清理了 ${keysToRemove.length} 个过期天气缓存`)
    }
  } catch (error) {
    console.error('清理过期天气缓存失败:', error)
  }
}

// 手动刷新天气数据
const refreshWeatherData = async () => {
  try {
    if (!selectedRegionText.value && userRegions.value.length > 0) {
      // 如果没有选中区域，使用第一个区域
      const firstRegion = userRegions.value[0]
      await fetchWeatherForSelectedRegion(firstRegion)
    } else if (selectedRegionText.value) {
      // 清除当前城市的缓存，强制重新获取
      const cityName = extractCityName(selectedRegionText.value)
      const cacheKey = WEATHER_CACHE_KEY + cityName
      localStorage.removeItem(cacheKey)
      await fetchWeatherData(cityName)
    } else {
      // 默认刷新北京天气
      const cacheKey = WEATHER_CACHE_KEY + '北京'
      localStorage.removeItem(cacheKey)
      await fetchWeatherData('北京')
    }
    console.log('天气数据已手动刷新')
  } catch (error) {
    console.error('刷新天气数据失败:', error)
  }
}

// 获取天气数据（集成一刻天气API）
const fetchWeatherData = async (cityName) => {
  try {
    // 首先检查缓存
    const cachedData = getCachedWeatherData(cityName)
    if (cachedData) {
      weatherData.value = cachedData
      return
    }
    
    console.log(`正在查询城市: ${cityName} - 调用一刻天气API`)
    
    // 使用一刻天气API接口 - v2030版本
    const weatherUrl = `http://gfeljm.tianqiapi.com/free/v2030?city=${encodeURIComponent(cityName)}&appid=74395762&appsecret=HKzoe1i5&hours=1&aqi=1&vue=1`
    console.log(`天气查询URL: ${weatherUrl}`)
    
    const weatherResponse = await fetch(weatherUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    })
    console.log(`天气查询响应状态: ${weatherResponse.status}`)
    
    if (!weatherResponse.ok) {
      console.warn(`天气数据API请求失败: ${weatherResponse.status} ${weatherResponse.statusText}`)
      throw new Error(`天气API请求失败: ${weatherResponse.status}`)
    }
    
    const weatherResponseText = await weatherResponse.text()
    console.log(`天气数据原始响应: ${weatherResponseText}`)
    
    let weatherResponseData
    try {
      weatherResponseData = JSON.parse(weatherResponseText)
    } catch (parseError) {
      console.error('解析天气数据响应失败:', parseError)
      throw new Error('天气响应解析失败')
    }
    
    console.log(`一刻天气API响应数据:`, weatherResponseData)
    
    // 检查API响应状态 - v2030版本检查
    if (!weatherResponseData || !weatherResponseData.city) {
      console.warn(`获取城市 ${cityName} 的天气数据失败，无有效数据`)
      throw new Error('天气数据获取失败')
    }
    
    // 生成天气提示信息
    const generateWeatherTips = (data) => {
      const currentWeather = data.wea || ''
      const hours = data.hours || []
      const aqi = data.aqi || {}
      
      // 检查是否有预警信息
      const alerts = data.alarm || []
      if (alerts.length > 0) {
        // 有预警时的特殊处理
        const hasRainAlert = alerts.some(alert => alert.alarm_type && alert.alarm_type.includes('暴雨'))
        const hasWindAlert = alerts.some(alert => alert.alarm_type && alert.alarm_type.includes('大风'))
        
        if (hasRainAlert && hasWindAlert) {
          return `今日有暴雨大风预警，请注意安全防护`
        } else if (hasRainAlert) {
          return `今日有暴雨预警，请注意防范积水`
        } else if (hasWindAlert) {
          return `今日有大风预警，请注意防风安全`
        }
      }
      
      // 检查空气质量
      if (aqi.air_level) {
        const airLevel = aqi.air_level
        if (airLevel === '重度污染' || airLevel === '严重污染') {
          return `今日${currentWeather}，空气质量${airLevel}，建议减少户外活动`
        } else if (airLevel === '中度污染' || airLevel === '轻度污染') {
          return `今日${currentWeather}，空气质量${airLevel}，外出请佩戴口罩`
        }
      }
      
      // 检查当前天气状况
      const rainKeywords = ['雨', '雷阵雨', '阵雨', '小雨', '中雨', '大雨', '暴雨']
      const isCurrentlyRaining = rainKeywords.some(keyword => currentWeather.includes(keyword))
      
      if (isCurrentlyRaining) {
        // 正在下雨，预测何时停止
        const rainEndHour = hours.find((hour, index) => 
          index > 0 && !rainKeywords.some(keyword => hour.wea?.includes(keyword))
        )
        
        if (rainEndHour) {
          const endHourIndex = hours.indexOf(rainEndHour)
          return `今日${currentWeather}，预计${endHourIndex}小时后停止`
        } else {
          return `今日${currentWeather}，预计持续一天`
        }
      }
      
      // 检查未来几小时是否有雨
      if (hours.length > 0) {
        const nextRainHour = hours.find((hour, index) => 
          index > 0 && rainKeywords.some(keyword => hour.wea?.includes(keyword))
        )
        
        if (nextRainHour) {
          const hourIndex = hours.indexOf(nextRainHour)
          return `预计${hourIndex}小时后下雨，请注意佩戴雨具`
        }
      }
      
      // 检查温度
      const temperature = parseInt(data.tem) || 0
      if (temperature > 30) {
        return `今日${currentWeather}，气温较高(${temperature}°C)，请注意防暑降温`
      } else if (temperature < 5) {
        return `今日${currentWeather}，气温较低(${temperature}°C)，请注意保暖`
      }
      
      // 默认晴朗天气提示
      if (currentWeather.includes('晴') || currentWeather.includes('多云')) {
        return '今日天气晴朗，工作愉快'
      }
      
      return `今日${currentWeather}，注意天气变化`
    }
    
    // 适配v2030版本API的数据结构
    const processedWeatherData = {
      temperature: parseInt(weatherResponseData.tem) || 0,
      humidity: parseInt(weatherResponseData.humidity?.replace('%', '')) || 0,
      city: weatherResponseData.city || cityName,
      description: weatherResponseData.wea || '未知',
      alerts: weatherResponseData.alarm || [], // v2030版本包含预警信息
      tips: generateWeatherTips(weatherResponseData),
      aqi: weatherResponseData.aqi || {}, // 空气质量指数信息
      hours: weatherResponseData.hours || [], // 小时天气预报
      updateTime: weatherResponseData.update_time || new Date().toLocaleString()
    }
    
    // 缓存天气数据
    setCachedWeatherData(cityName, processedWeatherData)
    
    weatherData.value = processedWeatherData
    console.log(`已获取 ${cityName} 的实时天气信息:`, weatherData.value)
  } catch (error) {
    console.error('获取真实天气数据失败:', error)
    // 设置默认天气信息作为备用
    const mockWeatherData = {
      '北京': { temperature: 23, humidity: 38, description: '晴', tips: '今日天气晴朗，工作愉快', alerts: [] },
      '上海': { temperature: 26, humidity: 45, description: '多云', tips: '今日天气晴朗，工作愉快', alerts: [] },
      '广州': { temperature: 28, humidity: 52, description: '小雨', tips: '今日小雨，预计持续一天', alerts: [] },
      '深圳': { temperature: 27, humidity: 48, description: '阴', tips: '今日阴天，注意天气变化', alerts: [] },
      '杭州': { temperature: 24, humidity: 42, description: '晴', tips: '今日天气晴朗，工作愉快', alerts: [] },
      '南京': { temperature: 22, humidity: 40, description: '多云', tips: '今日天气晴朗，工作愉快', alerts: [] },
      '成都': { temperature: 20, humidity: 55, description: '阴', tips: '今日阴天，注意天气变化', alerts: [] },
      '重庆': { temperature: 25, humidity: 50, description: '小雨', tips: '今日小雨，预计持续一天', alerts: [] },
    }
    
    const fallbackWeather = mockWeatherData[cityName] || mockWeatherData['北京']
    
    weatherData.value = {
      temperature: fallbackWeather.temperature,
      humidity: fallbackWeather.humidity,
      city: cityName || '北京',
      description: fallbackWeather.description,
      alerts: fallbackWeather.alerts || [],
      tips: fallbackWeather.tips
    }
    
    console.log(`使用备用天气数据:`, weatherData.value)
  }
}

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref(null)
const detailDetectionUser = ref(null)
const detailMaintenanceUser = ref(null)
const inspecAlbumExpanded = ref(false)
const maintainAlbumExpanded = ref(false)

// 处理活动点击
const handleActivityClick = async (activity) => {
  if (!activity.id) return
  detailDialogVisible.value = true
  detailLoading.value = true
  detailData.value = null
  detailDetectionUser.value = null
  detailMaintenanceUser.value = null

  try {
    const res = await getInformation(activity.id)
    if (res.code === 200 && res.data) {
      detailData.value = res.data

      // 查询检测人员
      if (res.data.detectionBy) {
        try {
          const userRes = await getUser(res.data.detectionBy)
          if (userRes.code === 200 && userRes.data) {
            detailDetectionUser.value = userRes.data
          }
        } catch (error) {
          console.error('获取检测人员信息失败:', error)
        }
      }

      // 查询维修人员
      if (res.data.maintenanceBy) {
        try {
          const userRes = await getUser(res.data.maintenanceBy)
          if (userRes.code === 200 && userRes.data) {
            detailMaintenanceUser.value = userRes.data
          }
        } catch (error) {
          console.error('获取维修人员信息失败:', error)
        }
      }
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 重置详情弹窗
const resetDetailDialog = () => {
  detailDialogVisible.value = false
  detailData.value = null
  detailDetectionUser.value = null
  detailMaintenanceUser.value = null
  inspecAlbumExpanded.value = false
  maintainAlbumExpanded.value = false
}

// 处理图片加载错误
const handleImageError = (event) => {
  event.target.style.display = 'none'
  const placeholder = event.target.parentNode.querySelector('.room-placeholder')
  if (placeholder) {
    placeholder.style.display = 'flex'
  }
}

onMounted(async () => {
  updateTime()
  setInterval(updateTime, 60000)
  window.addEventListener('storage', updateUserInfo)
  window.addEventListener('userInfoUpdated', updateUserInfo)
  
  // 清理过期的天气缓存
  clearExpiredWeatherCache()
  
  // 添加点击外部关闭下拉框的事件监听
  document.addEventListener('click', (event) => {
    const selectContainer = document.querySelector('.custom-select-container')
    if (selectContainer && !selectContainer.contains(event.target)) {
      dropdownOpen.value = false
    }
  })
  await loadUserInfoAndRole()
  if (userInfo.value && userInfo.value.userId) {
    await loadUserRegions(userInfo.value.userId)
    fetchRecentActivities()
    
    // 等待区域数据加载完成后，获取天气信息
    await fetchWeatherForUserRegions()
    
    // 获取工作提示
    await fetchWorkTips()
    
    // 设置默认选中第一个区域
    if (userRegions.value && userRegions.value.length > 0) {
      selectedRegionId.value = userRegions.value[0].id
      selectedRegionText.value = userRegions.value[0].regionName || userRegions.value[0].name
    }
  }
})

onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('storage', updateUserInfo)
  window.removeEventListener('userInfoUpdated', updateUserInfo)
  
  // 清理工作提示定时器
  stopWorkTipRotation()
})
</script>

<style lang="scss" scoped>
.home-page {
  // 透明容器，不影响背景渲染
  background: transparent;
  height: 100vh;
  max-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  // 覆盖layout的padding
  margin: -20px;
  padding: 0;
  
  @media (max-width: 768px) {
    margin: -15px;
    padding: 0;
    height: 100vh;
    max-height: 100vh;
  }
}

// 顶部用户信息区域
.header-section {
    padding: 30px 40px 10px 40px;
    flex-shrink: 0;
    
    @media (max-width: 768px) {
      padding: 25px 31px 8px 31px;
    }
    
    .user-info {
      .user-name {
        font-size: 24px;
        font-weight: 600;
        color: #ffffff;
        display: block;
        margin-bottom: 4px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
      }
      
      .date-info {
        font-size: 14px;
        color: #ffffff;
        font-weight: 400;
        text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
      }
    }
  }
  
  // 区域卡片横向滚动容器
  .rooms-container {
    padding: 15px 0 15px 0;
    background: none !important;
    background-color: transparent !important;
    flex-shrink: 0;
    
    .rooms-scroll {
      display: flex;
      gap: 20px;
      padding: 0 40px;
      overflow-x: auto;
      scroll-behavior: smooth;
      -webkit-overflow-scrolling: touch;
      background: none !important;
      background-color: transparent !important;
      background-image: none !important;
      box-shadow: none !important;
      border: none !important;
      outline: none !important;
      backdrop-filter: none !important;
      -webkit-backdrop-filter: none !important;
      
      // 隐藏滚动条但保持功能
      &::-webkit-scrollbar {
        display: none;
      }
      
      -ms-overflow-style: none;
      scrollbar-width: none;
    }
    
    .room-card {
      flex: 0 0 360px;
      background: rgba(255, 255, 255, 0.95);
      border: 1px solid rgba(255, 255, 255, 0.3);
      backdrop-filter: blur(20px);
      -webkit-backdrop-filter: blur(20px);
      border-radius: 48px;
      padding: 24px;
      overflow: hidden;
      box-shadow: 
        0 8px 32px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.4);
      cursor: pointer;
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        transform: translateY(-4px);
        background: rgba(255, 255, 255, 1);
        border-color: rgba(255, 255, 255, 0.4);
        box-shadow: 
          0 12px 40px rgba(0, 0, 0, 0.15),
          inset 0 1px 0 rgba(255, 255, 255, 0.5);
      }
      
      .room-image {
        width: 100%;
        height: 280px;
        position: relative;
        overflow: hidden;
        border-radius: 32px;
        background: rgba(255, 255, 255, 0.1);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          border-radius: 32px;
          transition: transform 0.3s ease;
        }
        
        .room-placeholder {
          width: 100%;
          height: 100%;
          background: rgba(255, 255, 255, 0.15);
          border: 1px solid rgba(255, 255, 255, 0.2);
          border-radius: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: rgba(120, 120, 120, 0.8);
          
          .el-icon {
            font-size: 72px;
          }
        }
      }
      
      .room-name {
        padding: 32px 24px 8px 24px;
        font-size: 32px;
        font-weight: 600;
        color: rgba(80, 80, 80, 0.9);
        text-align: center;
        background: transparent;
        letter-spacing: 0.4px;
        line-height: 1.3;
      }
      
      &:hover .room-image img {
        transform: scale(1.05);
      }
    }
  }
  
  // 控制面板
  .control-panel {
    flex: 1;
    display: flex;
    flex-direction: column;
    padding: 0;
    min-height: 0;
    width: 100%;
    overflow: hidden;
    
    .control-card {
      flex: 1;
      width: 100%;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 28px 28px 0 0;
      padding: 28px 24px 0 24px;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin: 0;
      overflow: hidden;
      
      .control-row {
        display: flex;
        align-items: center;
        margin-bottom: 0px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.weather-row {
          flex-direction: column;
          margin-bottom: 0px;
          
          .weather-info-row {
            display: flex;
            justify-content: space-between;
            width: 100%;
          }
          
          .weather-alert-container {
            width: 100%;
            margin-top: 8px;
            
            .clay-weather-alert {
              width: 100%;
              padding: 12px 16px;
              background: #f5f5f7;
              border-radius: 16px;
              box-shadow: 
                inset 2px 2px 4px rgba(0, 0, 0, 0.1),
                inset -2px -2px 4px rgba(255, 255, 255, 0.9),
                0 1px 3px rgba(0, 0, 0, 0.05);
              border: 1px solid rgba(0, 0, 0, 0.05);
              
              .weather-alert-text {
                font-size: 14px;
                color: #6b7280;
                font-weight: 400;
                line-height: 1.4;
                text-align: center;
                display: block;
              }
            }
          }
          
          .work-tips-container-inline {
            width: 100%;
            margin-top: 5px;
            background: #f5f5f7;
            border: 1px solid rgba(0, 0, 0, 0.05);
            border-radius: 16px;
            padding: 16px 20px;
            box-shadow: 
              inset 2px 2px 5px rgba(0, 0, 0, 0.1),
              inset -2px -2px 5px rgba(255, 255, 255, 0.9),
              0 1px 3px rgba(0, 0, 0, 0.05);
            
            .work-tips-header {
              margin-bottom: 12px;
              
              .work-tips-title {
                font-size: 16px;
                font-weight: 600;
                color: #374151;
              }
            }
            
            .work-tips-content {
              .work-tip-item {
                display: flex;
                align-items: center;
                padding: 8px 12px;
                background: rgba(255, 255, 255, 0.6);
                border-radius: 12px;
                box-shadow: 
                  inset 1px 1px 2px rgba(0, 0, 0, 0.05),
                  inset -1px -1px 2px rgba(255, 255, 255, 0.8);
                
                .work-tip-text {
                  font-size: 14px;
                  color: #6b7280;
                  font-weight: 400;
                  line-height: 1.4;
                  flex: 1;
                  
                  :deep(.region-highlight) {
                    color: #4A90E2;
                    font-weight: 600;
                    background: rgba(74, 144, 226, 0.1);
                    padding: 2px 6px;
                    border-radius: 6px;
                    border: 1px solid rgba(74, 144, 226, 0.2);
                  }
                }
              }
            }
          }
        }
        
        &.work-tips-row {
          margin-top: 5px;
          margin-bottom: 0px;
          
          .work-tips-container {
            width: 100%;
            background: #f5f5f7;
            border: 1px solid rgba(0, 0, 0, 0.05);
            border-radius: 16px;
            padding: 16px 20px;
            box-shadow: 
              inset 2px 2px 5px rgba(0, 0, 0, 0.1),
              inset -2px -2px 5px rgba(255, 255, 255, 0.9),
              0 1px 3px rgba(0, 0, 0, 0.05);
            
            .work-tips-header {
              margin-bottom: 12px;
              
              .work-tips-title {
                font-size: 16px;
                font-weight: 600;
                color: #374151;
              }
            }
            
            .work-tips-content {
              .work-tip-item {
                display: flex;
                align-items: center;
                padding: 8px 12px;
                background: rgba(255, 255, 255, 0.6);
                border-radius: 12px;
                box-shadow: 
                  inset 1px 1px 2px rgba(0, 0, 0, 0.05),
                  inset -1px -1px 2px rgba(255, 255, 255, 0.8);
                
                .work-tip-text {
                  font-size: 14px;
                  color: #6b7280;
                  font-weight: 400;
                  line-height: 1.4;
                  flex: 1;
                }
              }
            }
          }
        }
        
        .control-item {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 16px;
          
          &:not(:last-child) {
            margin-right: 32px;
          }
          
          .control-label {
            font-size: 15px;
            color: #7f8c8d;
            font-weight: 500;
            min-width: 80px;
          }
          
          .control-value {
            font-size: 22px;
            font-weight: 700;
            color: #2c3e50;
            letter-spacing: -0.5px;
          }
          
          .control-status {
            font-size: 13px;
            color: #27ae60;
            font-weight: 600;
            text-transform: lowercase;
            
            &.off {
              color: #95a5a6;
            }
          }
          
          // 天气信息特殊样式
          &.weather-temp, &.weather-humidity, &.weather-region {
            flex-direction: column;
            align-items: center;
            text-align: center;
            gap: 8px;
            
            .control-label {
              font-size: 14px;
              color: #7f8c8d;
              margin-bottom: 4px;
            }
            
            .control-value {
              font-size: 28px;
              font-weight: 700;
              color: #2c3e50;
            }
            
            .control-status {
              font-size: 12px;
              color: #7f8c8d;
              text-transform: none;
            }
            
            // 自定义下拉框样式
            &.weather-region {
              justify-content: center;
              
              .custom-select-container {
                position: relative;
                width: 140px;
                
                .custom-select {
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 12px 16px;
                  background: #f5f5f7;
                  border: 1px solid rgba(0, 0, 0, 0.05);
                  border-radius: 12px;
                  cursor: pointer;
                  transition: all 0.3s ease;
                  min-height: 44px;
                  box-shadow: 
                    inset 2px 2px 5px rgba(0, 0, 0, 0.1),
                    inset -2px -2px 5px rgba(255, 255, 255, 0.9),
                    0 1px 3px rgba(0, 0, 0, 0.05);
                  
                  .select-text {
                    font-size: 14px;
                    color: #6b7280;
                    font-weight: 400;
                    flex: 1;
                    text-align: center;
                  }
                  
                  .select-arrow {
                    width: 16px;
                    height: 16px;
                    color: #6b7280;
                    transition: transform 0.3s ease;
                    flex-shrink: 0;
                    
                    &.rotated {
                      transform: rotate(180deg);
                    }
                  }
                  
                  &:hover {
                    box-shadow: 
                      inset 1px 1px 3px rgba(0, 0, 0, 0.15),
                      inset -1px -1px 3px rgba(255, 255, 255, 1),
                      0 2px 6px rgba(0, 0, 0, 0.08);
                  }
                  
                  &.is-open {
                    box-shadow: 
                      inset 3px 3px 8px rgba(0, 0, 0, 0.15),
                      inset -3px -3px 8px rgba(255, 255, 255, 1);
                  }
                }
                
                .dropdown-menu {
                  position: absolute;
                  top: 100%;
                  left: 0;
                  right: 0;
                  background: #f5f5f7;
                  border: 1px solid rgba(0, 0, 0, 0.05);
                  border-radius: 12px;
                  margin-top: 4px;
                  max-height: 200px;
                  overflow-y: auto;
                  z-index: 1000;
                  box-shadow: 
                    0 4px 12px rgba(0, 0, 0, 0.15),
                    inset 1px 1px 2px rgba(255, 255, 255, 0.9);
                  
                  .dropdown-item {
                    padding: 12px 16px;
                    font-size: 14px;
                    color: #6b7280;
                    cursor: pointer;
                    transition: all 0.2s ease;
                    
                    &:hover {
                      background: rgba(255, 255, 255, 0.5);
                      color: #374151;
                    }
                    
                    &.selected {
                      background: rgba(107, 114, 128, 0.1);
                      color: #374151;
                      font-weight: 500;
                    }
                    
                    &:first-child {
                      border-radius: 12px 12px 0 0;
                    }
                    
                    &:last-child {
                      border-radius: 0 0 12px 12px;
                    }
                  }
                }
              }
            }
          }
          
          
          &.lights {
            flex-direction: column;
            align-items: flex-start;
            
            .control-slider {
              width: 100%;
              height: 6px;
              background: #ecf0f1;
              border-radius: 3px;
              position: relative;
              margin-top: 12px;
              
              .slider-fill {
                height: 100%;
                background: linear-gradient(90deg, #f39c12, #e74c3c);
                border-radius: 3px;
                transition: width 0.3s ease;
              }
            }
          }
          
          &.music {
            .music-controls {
              .music-dots {
                display: flex;
                gap: 5px;
                
                span {
                  width: 4px;
                  height: 14px;
                  background: #bdc3c7;
                  border-radius: 2px;
                  
                  &:nth-child(2) {
                    height: 18px;
                  }
                  
                  &:nth-child(3) {
                    height: 10px;
                  }
                  
                  &:nth-child(4) {
                    height: 16px;
                  }
                }
              }
            }
          }
          
          &.tv {
            .tv-channels {
              display: flex;
              gap: 10px;
              
              .channel {
                font-size: 11px;
                padding: 6px 12px;
                border-radius: 12px;
                background: #ecf0f1;
                color: #7f8c8d;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.3px;
                
                &.active {
                  background: #3498db;
                  color: white;
                  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
                }
              }
            }
          }
        }
      }
    }
  }
  
  // 区域标签列表样式
  .area-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    width: 100%;
    
    .area-tag {
      padding: 6px 12px;
      border-radius: 16px;
      font-size: 12px;
      font-weight: 500;
      background: #ecf0f1;
      color: #2c3e50;
      transition: all 0.3s ease;
      
      &.status-safe {
        background: rgba(39, 174, 96, 0.1);
        color: #27ae60;
        border: 1px solid rgba(39, 174, 96, 0.2);
      }
      
      &.status-unchecked {
        background: rgba(241, 196, 15, 0.1);
        color: #f1c40f;
        border: 1px solid rgba(241, 196, 15, 0.2);
      }
      
      &.status-maintenance {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border: 1px solid rgba(231, 76, 60, 0.2);
      }
      
      &.status-unknown {
        background: rgba(149, 165, 166, 0.1);
        color: #95a5a6;
        border: 1px solid rgba(149, 165, 166, 0.2);
      }
    }
  }

// 响应式设计 - 针对手机端优化
@media (max-width: 768px) {
  .header-section {
      .user-info .user-name {
        font-size: 22px;
      }
    }
    
    .rooms-container {
      padding: 16px 0 24px 0;
      background: none !important;
      background-color: transparent !important;
      
      .rooms-scroll {
        padding: 0 31px;
        gap: 16px;
        background: none !important;
        background-color: transparent !important;
        background-image: none !important;
        box-shadow: none !important;
        border: none !important;
        outline: none !important;
        backdrop-filter: none !important;
        -webkit-backdrop-filter: none !important;
      }
      
      .room-card {
        flex: 0 0 320px;
        padding: 20px;
        border-radius: 40px;
        
        .room-image {
          height: 240px;
          border-radius: 28px;
          
          img {
            border-radius: 28px;
          }
          
          .room-placeholder {
            border-radius: 28px;
            
            .el-icon {
              font-size: 60px;
            }
          }
        }
        
        .room-name {
          padding: 24px 16px 4px 16px;
          font-size: 28px;
        }
      }
    }
    
    .control-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      padding: 0;
      min-height: 0;
      width: 100%;
      overflow: hidden;
      
      .control-card {
        flex: 1;
        width: 100%;
        padding: 24px 20px 0 20px;
        border-radius: 24px 24px 0 0;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin: 0;
        overflow: hidden;
        
        .control-row {
          margin-bottom: 0px;
          
          &.weather-alert-row {
            margin-top: 8px;
          }
          
          .control-item {
            gap: 12px;
            
            &:not(:last-child) {
              margin-right: 24px;
            }
            
            .control-label {
              font-size: 14px;
              min-width: 70px;
            }
            
            .control-value {
              font-size: 20px;
            }
          }
        }
      }
    }
}

@media (max-width: 480px) {
  .header-section {
    .user-info .user-name {
      font-size: 20px;
      color: #ffffff;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
    }
  }
  
  .rooms-container .rooms-scroll .room-card {
    flex: 0 0 280px;
    padding: 16px;
    border-radius: 36px;
    
    .room-image {
      height: 200px;
      border-radius: 24px;
      
      img {
        border-radius: 24px;
      }
      
      .room-placeholder {
        border-radius: 24px;
        
        .el-icon {
          font-size: 52px;
        }
      }
    }
    
    .room-name {
      font-size: 26px;
      padding: 20px 12px 4px 12px;
    }
  }
  
  .control-panel .control-card .control-row {
    gap: 16px;
    
    .control-item {
      width: 100%;
      margin-right: 0 !important;
      
      &.lights .control-slider {
        margin-top: 10px;
      }
    }
  }
}
</style>